package org.letva.toink.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.letva.toink.dao.GenericDao;
import org.letva.toink.model.ToinkEntity;
import org.letva.toink.util.HibernateUtil;

@SuppressWarnings("unchecked")
public class GenericDaoImpl implements GenericDao {
    private Session session;

    @Override
    public <T extends ToinkEntity> T getById(Long id, Class<T> clazz) {
    	session = HibernateUtil.getSession();
        return (T) session.get(clazz, id);
    }

    @Override
    public <T extends ToinkEntity> List<T> findAll(Class<T> clazz) {
    	session = HibernateUtil.getSession();
        return session.createCriteria(clazz).list();
    }

    @Override
    public <T extends ToinkEntity> void saveOrUpdate(T entity) {
    	session = HibernateUtil.getSession();
        session.beginTransaction();
        session.saveOrUpdate(entity);
        session.getTransaction().commit();
    }

    @Override
	public <T extends ToinkEntity> List<T> findByExample(T example) {
    	session = HibernateUtil.getSession();
        Example ex = Example.create(example);
        Criteria c = session.createCriteria(example.getClass()).add(ex);
        return (List<T>) c.list();
    }
	
    @Override
	public <T extends ToinkEntity> void delete(T entity) {
		session = HibernateUtil.getSession();
		session.beginTransaction();
		session.delete(entity);
		session.getTransaction().commit();
	}

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }


}
